package xyz.yuanjilu.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;

import xyz.yuanjilu.mqentity.Person;
import xyz.yuanjilu.service.MQConsumer;
import xyz.yuanjilu.utils.RRException;

public class DemoConsumer implements MQConsumer{
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
    private AmqpTemplate amqpTemplate;
	
	@Override
    public void onMessage(Message message) {
       logger.info(this.toString()+"处理消息");
	   String responseMessage="";
	   Person person=null;
        try {
            //将字节流对象转换成Java对象
            person=(Person) new ObjectInputStream(new ByteArrayInputStream(message.getBody())).readObject();
            responseMessage = "欢迎：姓名"+person.getName()+"年龄："+person.getAge();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (person==null) {
			throw new RRException("消息错误");
		}
        if (person.getAge()%2==0) {
        	//throw new RRException("年龄错误");
		}
        String replyTo = message.getMessageProperties().getReplyTo();
        MessageConverter messageConverter=new SimpleMessageConverter();
        
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.getHeaders().putAll(message.getMessageProperties().getHeaders());
        messageProperties.setCorrelationId(message.getMessageProperties().getCorrelationId());
        //将Java对象转成Message对象，并作为返回的内容，回送给生产者
        Message message2=messageConverter.toMessage(responseMessage, messageProperties);
        amqpTemplate.send(replyTo, message2);
        
        
    }

}
